from django.shortcuts import render
from django.views import View
from django.core.cache import cache
from django import http

from .models import Area
from meiduo_mall.utils.response_code import RETCODE
# Create your views here.


class AreasView(View):
    """省市区数据查询"""

    def get(self, request):
        """提供省市数据"""
        # 提取需要获取的area_id
        area_id = request.GET.get('area_id')
        if not area_id:
            # 提供省份信息

            # 先尝试性的去redis获取所有省的数据
            province_list = cache.get('province_list')
            if province_list is None:
                # 如果redis没有， 从mysql获取省的查询集
                province_model_qs = Area.objects.filter(parent=None)
                province_list = []
                for province in province_model_qs:

                    province_dict = {
                        'id': province.id,
                        'name': province.name
                    }
                    province_list.append(province_dict)
                    # 存储缓存数据：cache.set('key', 内容, 有效期)
                    cache.set('province_list', province_list, 3600)

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'province_list': province_list})
        else:   # 有省市信息area_id
            area_data = cache.get('area_data_%s' % area_id)
            try:
                area_model = Area.objects.get(id=area_id) # 此模型可能是某个市或者某个省
            except Area.DoesNotExist:
                http.HttpResponseForbidden('区域不存在')
            subs_model_qs = area_model.subs.all()
            sub_list = []  # 用来装下级行政区字典
            for sub in subs_model_qs:
                sub_dict = {
                    'id': sub.id,
                    'name':sub.name
                }
                sub_list.append(sub_dict)
            sub_data = {
                'id': area_id,
                'name': area_model.name,
                'subs': sub_list
            }
            cache.set('sub_data_%s' % area_id, sub_data, 3600)
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': sub_data})
